<?php
/*
# $Id$
#
# This is the ONLY script in this folder that is scheduled to be executed.
# It in turn executes all separate scripts in this folder.
*/

// Set memory and execution time limits
ini_set('memory_limit', (1024*1024)*256);	// 256MB limit
set_time_limit(60*30);						// 30 minutes limit

// Init Buan
define('CRON', TRUE);
require(dirname(dirname(__FILE__)).'/buan/Buan.php');
use Buan\Config;
use Buan\Core;
use Buan\SystemLog;

Core::configure(dirname(dirname(__FILE__)).'/config');

// Sandbox function for executing scripts
function __cronSandbox($src) {
	$__lastRunFile = Config::get('app.cron.dir.log').'/'.basename($src).'.lastrun';
	$__lastRunTime = file_exists($__lastRunFile) ? filemtime($__lastRunFile) : 0;
	$__result = include($src);
	if($__result==1) {
		if(!file_exists($__lastRunFile)) {
			file_put_contents($__lastRunFile, "created");
		}
		else {
			touch($__lastRunFile);
		}
	}
}

// Execute scripts
// Lock files are created and destroyed for each individual script which goes
// some way to preventing a job being executed on more than 1 thread at a time.
$__scripts = array(
	'build-sitemap.php',
	'backup-db.php',
	'backup-site.php',
	'send-emails.php'
);
foreach($__scripts as $__script) {

	// Test/create lock file
	// If the lock file is still present more than 10 minutes after being created
	// then assume something went wrong with the previous thread and continue
	// executing it.
	$lockFile = Config::get('app.cron.dir.log').'/cron.'.basename($__script).'.lock';
	if(file_exists($lockFile)) {
		if(filemtime($lockFile)<time()-(60*10)) {
			touch($lockFile);
		}
		else {
			SystemLog::add("{$__script}: Script is locked.");
			continue;
		}
	}
	else if(file_put_contents($lockFile, "created")===FALSE) {
		SystemLog::add("{$__script}: Failed to create lock file.");
		continue;
	}

	// Execute script
	__cronSandbox(dirname(__FILE__)."/{$__script}");

	// Remove lock
	if(!unlink($lockFile)) {
		SystemLog::add("{$__script}: Failed to remove lock file.");
		continue;
	}
}

// Write messages to log (ignore "core" errors)
$logs = SystemLog::getAll();
if(!empty($logs)) {
	if($fd = fopen(Config::get('app.cron.dir.log').'/error.log', 'ab')) {
		foreach($logs as $log) {
			if($log->getType()!=SystemLog::CORE) {
				fwrite($fd, "[".date("d-m-Y H:i:s", time())."] [".$log->getTypeString()."] ".$log->getMessage()."\n");
			}
		}
		fclose($fd);
	}
}
exit(0);
?>